package com.byd.demo;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.apis.ClientConfiguration;
import org.apache.rocketmq.client.apis.ClientConfigurationBuilder;
import org.apache.rocketmq.client.apis.ClientException;
import org.apache.rocketmq.client.apis.ClientServiceProvider;
import org.apache.rocketmq.client.apis.message.Message;
import org.apache.rocketmq.client.apis.producer.Producer;
import org.apache.rocketmq.client.apis.producer.SendReceipt;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author jinsuo.lin@definesys.com
 * @Description TODO
 * @Version 1.0.0
 * @Date 2023/3/12 16:57
 */
@Component
@Slf4j
public class DemoProducer {
    @Value("${rocketmq.endpoint}")
    private String endpoint;
    private static final String TOPIC = "OAInstance";
    private ClientServiceProvider provider;
    private Producer producer;

    @PostConstruct
    public void initDemoProducer() throws ClientException {
        provider = ClientServiceProvider.loadService();
        ClientConfigurationBuilder builder = ClientConfiguration.newBuilder().setEndpoints(endpoint);
        ClientConfiguration configuration = builder.build();
        producer = provider.newProducerBuilder()
                .setTopics(TOPIC)
                .setClientConfiguration(configuration)
                .build();
    }

    public boolean sendMessage(String tag,DemoDto demoDto){

        String msgJson = JSON.toJSONString(demoDto);
        log.info(msgJson);
        Message message = provider.newMessageBuilder()
                .setTopic(TOPIC)
                // 设置消息索引键，可根据关键字精确查找某条消息。
                .setKeys("messageKey")
                // 设置消息Tag，用于消费端根据指定Tag过滤消息。
                .setTag(tag)
                // 消息体。
                .setBody(msgJson.getBytes())
                .build();
        try {
            // 发送消息，需要关注发送结果，并捕获失败等异常。
            SendReceipt sendReceipt = producer.send(message);
            log.info("Send message successfully, messageId={}", sendReceipt.getMessageId());
        } catch (ClientException e) {
            log.error("Failed to send message", e);
            return false;
        }
        return true;
    }
}
